<template>
    <div v-show="initShow && isUseDraw" class="layout">
        <div class="container">
            <ZWGroup
                ref="GroupingRef"
                :type="16"
                :group-id="group_id"
                :auth-code="authCode"
                @submit="handleGroupSubmit" />
            <div class="container_right">
                <div class="container-form">
                    <ZwSearchForm
                        row-num="4"
                        :option="searchOption"
                        :default-expand="false"
                        @search="onSearch"
                        @reset="reset"
                        @expand="expandHandle" />
                </div>
                <div class="container-table">
                    <ZwTable
                        ref="tableRef"
                        :tab-h="`calc(100vh - 284px - ${state.searchHeight})`"
                        :option="tableOption"
                        :row-key="getRowKey"
                        :fetch-params="state.searchParams"
                        :fetch-api="fetchApi()"
                        :close-loading="true"
                        @select="onSelect"
                        @selection-change="onSelectionChange"
                        @select-all="onSelectAll"
                        @dataChange="dataChange">
                        <template #headerOperate>
                            <el-dropdown v-auth="'ADD'" class="dropdown_button">
                                <el-button :disabled="checkList.length == 0">
                                    批量操作
                                    <el-icon class="el-icon--right"> <arrow-down /> </el-icon>
                                </el-button>
                                <template #dropdown>
                                    <el-dropdown-menu>
                                        <el-dropdown-item v-auth="'BATCH_DOWN_LOAD'" @click="onChange(3)">
                                            批量下载
                                        </el-dropdown-item>
                                        <el-dropdown-item v-auth="'BATCH_DEL'" @click="onChange(0)">
                                            批量删除
                                        </el-dropdown-item>
                                    </el-dropdown-menu>
                                </template>
                            </el-dropdown>
                            <el-dropdown v-auth="'ADD'" class="dropdown_button">
                                <el-button type="primary">
                                    新建活动
                                    <el-icon class="el-icon--right"> <arrow-down /> </el-icon>
                                </el-button>
                                <template #dropdown>
                                    <el-dropdown-menu>
                                        <el-dropdown-item @click="toCreateActivity('1')">普通裂变</el-dropdown-item>
                                        <el-dropdown-item @click="toCreateActivity('2')">高级裂变</el-dropdown-item>
                                    </el-dropdown-menu>
                                </template>
                            </el-dropdown>
                        </template>
                    </ZwTable>
                </div>
            </div>
        </div>
    </div>
    <NoData v-show="initShow && !isUseDraw" @submit="goUse"></NoData>
    <!-- 删除弹框 -->
    <ZWDeletdialog ref="DeletdialogRef" @submit="onSubmit" />
</template>

<script lang="tsx">
import { defineComponent } from 'vue';
// 定义name专用script标签
// eslint-disable-next-line vue/component-definition-name-casing
export default defineComponent({ name: 'SMART_MARKETING_FISSION_FISSION_DRAINAGE' });
</script>

<script setup lang="tsx">
import { ref, reactive, computed, onMounted, nextTick, onActivated } from 'vue';
import { Picture as IconPicture, ArrowDown, QuestionFilled } from '@element-plus/icons-vue';
import ZwSearchForm from '@/components/zw/search-form1.0/SearchForm';
import NoData from './components/NotData.vue';
import ZwTable from '@/components/zw/table1.0/Table';
import ZWDeletdialog from '@/components/ZWDeletdialog.vue';
import ZWGroup from '@/components/ZWGroup.vue';
import useClipboard from 'vue-clipboard3';
import { ElMessage, ElImage, ElIcon, ElButton } from 'element-plus';
import {
    getFissionList,
    download,
    deleteFission,
    changeStatus,
    getEmployeeList,
    toExportCode
} from '@/api/smartMarketing/fissionDrainage';
import { getCreateList } from '@/api/common';
import { useRouter, useRoute } from 'vue-router';
import { deepCopy } from '@/utils/helper';
import { DOWLOAD_FILE } from '@/utils/smartMarketing';
import { reSize } from '@/utils/utils';
import { endLoading, startLoading } from '@/utils/request';
import { ShowTaskMessage } from '@/hooks/TaskMessageHooks';
import { isCachePage } from '@/utils/utils';
import { parabolaAnimation } from '@/utils/parabola';

import { useStore } from '@/store';
const store = useStore();
const DeletdialogRef: any = ref(null);
const router = useRouter();
const GroupingRef: any = ref(null);
const tableRef: any = ref<HTMLElement | null>(null);
const isShow = ref(0);
const checkList = ref([]);
const employeList: any = ref([]); // 引流成员options
const delId = ref('');
const requestFlag = ref<boolean>(false);
const checkNum = ref<number>(0);
const currentParams = ref<any>(null);
const group_id = ref<string>('all');
const initShow = ref<boolean>(false);
const isUseDraw = ref(false); // 是否是当前企业
const route = useRoute();
const defaultParams = {
    group_id: 'all',
    activity_name: '', //活动标题
    created_uid: '', //创建人id
    employee_ids: [], //引流员工
    activity_status: 0, //活动状态 0-全部 1-未开始 2-进行中 3-已结束 4-提前结束
    create_time: [] //创建时间
};

// 分组权限code码
const authCode = {
    add: 'ADD_CHILD_GROUP',
    edit: 'EDIT_CHILD_GROUP',
    del: 'DEL_CHILD_GROUP'
};
const handleGroupSubmit = (v: any) => {
    router.push({
        path: '/smartMarketing/fission/fissionDrainage',
        query: { group_id: v.id }
    });
    group_id.value = v.id;
    currentParams.value = { ...deepCopy(defaultParams), ...currentParams.value, group_id: group_id.value };
    state.searchParams = deepCopy(currentParams.value);
    tableRef.value?.clearSelection();
};
// 复制
const { toClipboard } = useClipboard();
const onCopy = async (v: any) => {
    try {
        await toClipboard(v);
        ElMessage.success('复制成功');
    } catch (e) {
        ElMessage.error('复制失败');
    }
};

// 表格的自适应高度
const getTableH = () => {
    nextTick(() => {
        tableRef.value.getTableH();
    });
};
const state = reactive({
    searchParams: deepCopy(defaultParams),
    searchHeight: '64px'
});
const searchOption = computed(() => {
    return [
        {
            label: '活动名称',
            name: 'activity_name',
            value: '',
            type: 'input',
            placeholder: '请输入活动名称'
        },
        {
            label: '活动状态',
            name: 'activity_status',
            value: '',
            type: 'select',
            placeholder: '请选择活动状态',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    setTimeout(() => {
                        resolve([
                            { name: '全部', id: '0' },
                            { name: '未开始', id: '1' },
                            { name: '进行中', id: '2' },
                            { name: '已结束', id: '3' },
                            { name: '提前结束', id: '4' }
                        ]);
                    }, 300);
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '创建人',
            name: 'created_uid',
            value: [],
            multiple: true,
            type: 'select',
            filterable: true,
            placeholder: '请选择创建人',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    getCreateList({}).then((res: any) => {
                        const targetArr = res.map((item: any) => {
                            item.name = `${item.name}  (${item.phone})`;
                            return item;
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '引流员工',
            name: 'employee_ids',
            value: '',
            type: 'select',
            placeholder: '请选择引流员工',
            multiple: true,
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    resolve(employeList.value);
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '创建时间',
            name: 'create_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
        }
    ];
});
const onSearch = (v: any) => {
    tableRef.value?.clearSelection();
    currentParams.value = {
        ...deepCopy(defaultParams),
        ...v,
        group_id: group_id.value
    };
    state.searchParams = deepCopy(currentParams.value);
};
const reset = (v: any) => {
    tableRef.value?.clearSelection();
    currentParams.value = { ...deepCopy(defaultParams), group_id: group_id.value };
    state.searchParams = deepCopy(currentParams.value);
};
/**
 * @description: 展开收起
 */
const expandHandle = (expand: boolean) => {
    state.searchHeight = expand ? '112px' : '64px';
};

const onDownload = async (row: any) => {
    const res = await download({ activity_ids: [row.id] });
    DOWLOAD_FILE(res.url, res.name);
    // tableRef.value?.clearSelection();
};
getEmployeeList().then((res: any) => {
    // employeList.value = res.sort((a: any, b: any) => a.name.localeCompare(b.name, 'zh'))
    employeList.value = res;
    // employeOptions.value = employeList.value
});

// 按钮是否显示
const createIsRender = (authState: any[]) => {
    return ({ row }: any) => authState.includes(row.activity_status);
};
// 状态颜色
const StatusColorOption = {
    未开始: '#FFD500',
    进行中: '#2FB6E4',
    已结束: '#F14144',
    提前结束: '#ff0004'
};
// 表格
const tableOption = [
    {
        type: 'selection',
        width: 55,
        fixed: 'left',
        reserveSelection: true
    },
    {
        prop: 'activity_name',
        label: '标题',
        width: 130,
        showOverflowTooltip: true
    },
    {
        prop: 'qr_code_link',
        label: '二维码',
        align: 'center',
        width: 100,
        render({ row, column, index }) {
            const slotError = () => (
                <div class="image-slot">
                    <ElIcon>
                        <IconPicture />
                    </ElIcon>
                </div>
            );
            return (
                <>
                    <ElImage
                        preview-src-list={[row.qr_code_link]}
                        preview-teleported={true}
                        src={row.qr_code_link}
                        style="width: 48px; height: 48px; font-size: 49px"
                        vSlots={{ error: slotError }}
                    />
                </>
            );
        }
    },
    {
        prop: 'activity_status',
        label: '活动状态',
        minWidth: 100,
        render({ row, column, index }) {
            return (
                <div
                    class="status-point"
                    style={{
                        '--status-bgcolor': StatusColorOption[row.activity_status] ?? '#D8D8D8'
                    }}>
                    {row.activity_status}
                </div>
            );
        }
    },
    {
        prop: 'activity_type_name',
        width: 120,
        renderHeader({ row }) {
            const slotContent = () => (
                <p>
                    <p>普通裂变：企微引流</p>
                    <p>高级裂变：企微引流 + 公众号</p>
                </p>
            );
            return (
                <p class="tableHeader">
                    <span>活动类型</span>
                    <el-tooltip vSlots={{ content: slotContent }} placement="top">
                        <ElIcon class="tip-box">
                            <QuestionFilled />
                        </ElIcon>
                    </el-tooltip>
                </p>
            );
        },
        render({ row }) {
            return <div>{row.activity_type === 1 ? '普通裂变' : '高级裂变'}</div>;
        }
    },
    {
        prop: 'effective_time',
        label: '活动有效期',
        width: 200,
        render({ row, column, index }) {
            return (
                <>
                    {row.period_type == 1 ? (
                        '永久'
                    ) : (
                        <div>
                            <p>{row.effect_time[0]}</p>
                            <p>至</p>
                            <p>{row.effect_time[1]}</p>
                        </div>
                    )}
                </>
            );
        }
    },
    {
        prop: 'participate_num',
        label: '参与客户数',
        width: 130,
        header: true,
        renderHeader({ row }) {
            const slotContent = () => <p>进入活动并加好友的人数（包含已删除好友）</p>;
            return (
                <p class="tableHeader">
                    <span>参与客户数</span>
                    <el-tooltip vSlots={{ content: slotContent }} placement="top">
                        <ElIcon class="tip-box">
                            <QuestionFilled />
                        </ElIcon>
                    </el-tooltip>
                </p>
            );
        }
    },

    {
        prop: 'guest_num',
        label: '获客数量',
        width: 120,
        header: true,
        renderHeader({ row }) {
            const slotContent = () => (
                <p>
                    通过该客户裂变的添加企业员工好友的 <br />
                    客户数量（包括已删除的好友的客户）
                </p>
            );
            return (
                <p class="tableHeader">
                    <span>获客数量</span>
                    <el-tooltip vSlots={{ content: slotContent }} placement="top">
                        <ElIcon class="tip-box">
                            <QuestionFilled />
                        </ElIcon>
                    </el-tooltip>
                </p>
            );
        }
    },
    {
        prop: 'lost_num',
        label: '流失客户数',
        width: 130,
        header: true,
        renderHeader({ row }) {
            const slotContent = () => <p>通过该活动添加好友后又删除好友的客户数</p>;
            return (
                <p class="tableHeader">
                    <span>流失客户数</span>
                    <el-tooltip vSlots={{ content: slotContent }} placement="top">
                        <ElIcon class="tip-box">
                            <QuestionFilled />
                        </ElIcon>
                    </el-tooltip>
                </p>
            );
        }
    },
    {
        prop: 'follow_fan_num',
        label: '粉丝关注数',
        width: 130,
        header: true,
        renderHeader({ row }) {
            const slotContent = () => <p>通过该客户裂变的粉丝数（包括取关的粉丝数）</p>;
            return (
                <p class="tableHeader">
                    <span>粉丝关注数</span>
                    <el-tooltip vSlots={{ content: slotContent }} placement="top">
                        <ElIcon class="tip-box">
                            <QuestionFilled />
                        </ElIcon>
                    </el-tooltip>
                </p>
            );
        }
    },
    {
        prop: 'un_follow_fan_num',
        label: '取关粉丝数',
        width: 130,
        header: true,
        renderHeader({ row }) {
            const slotContent = () => <p>通过该客户关注的公众号粉丝又取消关注的数量</p>;
            return (
                <p class="tableHeader">
                    <span>取关粉丝数</span>
                    <el-tooltip vSlots={{ content: slotContent }} placement="top">
                        <ElIcon class="tip-box">
                            <QuestionFilled />
                        </ElIcon>
                    </el-tooltip>
                </p>
            );
        }
    },
    {
        prop: 'employee',
        label: '引流成员',
        width: 170,
        showOverflowTooltip: true,
        header: true
    },

    {
        prop: 'group_name',
        label: '所属分组',
        align: 'center',
        width: 150
    },
    {
        prop: 'created_user',
        label: '创建人',
        width: 150
    },
    {
        prop: 'created_at',
        label: '创建时间',
        width: 180
    },
    {
        prop: 'operate',
        label: '操作',
        width: 220,
        fixed: 'right',
        isOperate: true,
        option: [
            {
                name: '查看',
                authCode: 'LOOK',
                click: (row: any) => goActive('look', row)
            },
            {
                name: '统计',
                authCode: 'STATISTICS',
                isRender: createIsRender(['进行中', '已结束', '提前结束']),
                click: (row: any) => router.push(`/smartMarketing/fission/fissionDrainage/statistics?id=${row.id}`)
            },
            {
                name: '参与者',
                authCode: 'STATISTICS',
                isRender: createIsRender(['进行中', '已结束', '提前结束']),
                click: (row: any) => router.push(`/smartMarketing/fission/fissionDrainage/participant?id=${row.id}`)
            },
            {
                name: '结束',
                authCode: 'SWITCH',
                isRender: createIsRender(['进行中']),
                click: (row: any) => {
                    delId.value = row.id;
                    onChange(6);
                }
            },
            {
                name: '开始',
                authCode: 'SWITCH',
                isRender: createIsRender(['未开始']),
                click: (row: any) => {
                    delId.value = row.id;
                    onChange(5);
                }
            },
            {
                name: '编辑',
                authCode: 'EDIT',
                isRender: createIsRender(['未开始', '进行中']),
                click: (row: any) => goActive('edit', row)
            },
            {
                name: '下载',
                authCode: 'DOWN_LOAD',
                isRender: createIsRender(['未开始', '进行中']),
                click: (row: any) => onDownload(row)
            },
            {
                name: '导出兑奖码',
                authCode: 'DOWN_LOAD',
                isRender: ({ row }: any) => !!row.has_export_file,
                click: (row: any, column: any, index: any, e: any) => onExportCode(row, e)
            },
            {
                name: '复制链接',
                authCode: 'COPY_LINK',
                isRender: createIsRender(['未开始', '进行中']),
                click: (row: any) => onCopy(row.activity_url)
            },
            {
                name: '删除',
                authCode: 'DEL',
                click: (row: any) => {
                    delId.value = row.id;
                    onChange(4);
                }
            }
        ]
    }
];

const onExportCode = (row: any, e: any) => {
    const params = {
        activity_id: row.id
    };
    toExportCode(params).then(() => {
        parabolaAnimation(e);
        ShowTaskMessage('导出兑奖码异步任务创建成功');
    });
};
const getRowKey = (row: any) => {
    return row.id;
};

const fetchApi = () => {
    getTableH();
    // 获取文件列表
    return getFissionList;
};
// 选中表格 checkbox
const onSelect = (selection, row) => {
    if (selection.constructor === Array) checkList.value = selection.map(v => v.id);
};
// 选择项变更
const onSelectionChange = selection => {};
// 全选
const onSelectAll = selection => {
    checkList.value = selection.map(v => v.id);
};
// 刷新表格
const reloadTable = () => {
    tableRef.value.reload();
};
// 导出表格数据
const exportTableData = () => {};
const onChange = (num: number) => {
    switch (num) {
        case 0:
            DeletdialogRef.value.appDialog.title = '删除提醒';
            DeletdialogRef.value.content = '确认删除所选活动吗？';
            break;
        case 3:
            DeletdialogRef.value.appDialog.title = '下载提醒';
            DeletdialogRef.value.content = '确认下载所选活动吗？';
            break;
        case 4:
            DeletdialogRef.value.appDialog.title = '删除提醒';
            DeletdialogRef.value.content = '确认删除所选活动吗？';
            break;
        case 5:
            DeletdialogRef.value.appDialog.title = '开始提醒';
            DeletdialogRef.value.content = '确认开始当前活动吗？';
            break;
        case 6:
            DeletdialogRef.value.appDialog.title = '结束提醒';
            DeletdialogRef.value.content = '确认结束当前活动吗？';
            break;
    }
    isShow.value = num;
    DeletdialogRef.value.appDialog.visible = true;
};
const onSubmit = async () => {
    startLoading();
    try {
        switch (isShow.value) {
            case 0:
                await deleteFission({ activity_ids: checkList.value });
                ElMessage.success('删除成功');
                DeletdialogRef.value.appDialog.visible = false;
                tableRef.value.reload();
                await GroupingRef.value.getGroup(16);
                state.searchParams = { ...deepCopy(defaultParams), ...currentParams.value };
                break;
            case 3:
                // eslint-disable-next-line no-case-declarations
                const res = await download({ activity_ids: checkList.value });
                DOWLOAD_FILE(res.url, res.name);
                ElMessage.success('活动下载成功');
                DeletdialogRef.value.appDialog.visible = false;
                break;
            case 4:
                await deleteFission({ activity_ids: [delId.value] });
                ElMessage.success('删除成功');
                DeletdialogRef.value.appDialog.visible = false;
                await GroupingRef.value.getGroup(16);
                state.searchParams = { ...deepCopy(defaultParams), ...currentParams.value };
                break;
            case 5:
                await changeStatus({ activity_id: delId.value, status: 1 });
                ElMessage.success('活动开始成功');
                DeletdialogRef.value.appDialog.visible = false;
                tableRef.value.reload();
                break;
            case 6:
                await changeStatus({ activity_id: delId.value, status: 2 });
                ElMessage.success('活动结束成功');
                DeletdialogRef.value.appDialog.visible = false;
                tableRef.value.reload();
                break;
        }
    } catch (error) {
        endLoading();
    }
    tableRef.value?.clearSelection();
};
const getQuery = (t: string, row: any) => {
    const q = {
        type: t,
        id: row.id,
        title: row.activity_name
    };
    return q;
};
// 新增活动
const toCreateActivity = (create_type: string) => {
    router.push({
        path:
            create_type == '1'
                ? '/smartMarketing/fission/fissionDrainage/ordinary'
                : '/smartMarketing/fission/fissionDrainage/senior',
        query: { group_id: group_id.value, create_type }
    });
};
// 去活动
const goActive = (pageType: string, row: any) => {
    if (pageType == 'look') {
        router.push({
            path:
                row.activity_type == '1'
                    ? '/smartMarketing/fission/fissionDrainage/ordina/lookActive'
                    : '/smartMarketing/fission/fissionDrainage/senior/lookActive',
            query: { type: pageType, id: row.id }
        });
    } else {
        router.push({
            path:
                row.activity_type == '1'
                    ? '/smartMarketing/fission/fissionDrainage/ordina/editActive'
                    : '/smartMarketing/fission/fissionDrainage/senior/editActive',
            query: { type: pageType, id: row.id }
        });
    }
};
const dataChange = (res: any) => {
    res.data.forEach(item => {
        item.employee = Array.isArray(item.employee) ? item.employee.join('、') : '--';
    });
    if (res.data) initShow.value = true;
    if (checkNum.value === 0) {
        const currentCorp = store.getters['user/getCurrentCorp'];
        const isUser = JSON.parse(localStorage.getItem('zw-isDraw-fissionDrainage'));
        if (res.data.length == 0) {
            if (isUser && isUser == currentCorp) {
                isUseDraw.value = true;
            } else {
                isUseDraw.value = false;
            }
        } else {
            isUseDraw.value = true;
        }
    }
    checkNum.value++;
};
// 判断是否是当前企业
const isCurrentFirm = () => {
    getFissionList({ page: 1, page_size: 15, ...defaultParams, group_id: 'all' }).then((res: any) => {
        const currentCorp = store.getters['user/getCurrentCorp'];
        const isUser = JSON.parse(localStorage.getItem('zw-isDraw-fissionDrainage'));
        if (res.data.length == 0) {
            if (isUser && isUser == currentCorp) {
                isUseDraw.value = true;
            } else {
                isUseDraw.value = false;
            }
        } else {
            isUseDraw.value = true;
        }
    });
};
// 去跳转列表页
const goUse = (data: number | string) => {
    localStorage.setItem('zw-isDraw-fissionDrainage', JSON.stringify(data));
    isCurrentFirm();
};
const onExpand = () => {
    getTableH();
};
onMounted(() => {
    // isCurrentFirm();
    reSize(getTableH);
});
onActivated(async (val: any) => {
    const groupId = Number(route.params?.group_id || route.query?.group_id);
    if (isCachePage() || groupId || groupId == 0) {
        if ((groupId || groupId == 0) && group_id.value != groupId) {
            group_id.value = groupId;
        } else {
            await GroupingRef.value.getGroup(16);
        }
        tableRef.value?.clearSelection();
        GroupingRef.value.setCurrentSelectId({ id: group_id.value });
        state.searchParams = {
            ...deepCopy(defaultParams),
            ...currentParams.value,
            group_id: groupId || group_id.value
        };
    }
});
</script>

<style lang="scss" scoped>
.layout {
    height: calc(100vh - 142px);
    display: flex;
    flex-direction: column;

    .container {
        flex: 1;
        display: flex;
        overflow: hidden;

        .container_right {
            flex: 1;
            display: flex;
            flex-direction: column;
            box-sizing: border-box;
            overflow: hidden;

            .container-form {
                padding: 0 8px;
                border: 1px solid #eaeaea;
            }

            .container-table {
                flex: 1;
                display: flex;
                flex-direction: column;
                margin-top: 16px;
                background-color: #fff;
                padding: 16px 24px;
                border: 1px solid #eaeaea;

                .zw-table {
                    display: flex;
                    flex-direction: column;
                    flex: 1;
                    overflow: hidden;

                    :deep(.el-table) {
                        flex: 1;

                        .el-table__empty-block {
                            position: absolute;
                            top: 50%;
                            left: 50%;
                            transform: translate(-50%, -50%);
                        }
                    }
                }
            }
        }
    }
}

.dropdown_button {
    padding: 0 10px;
}

:deep(.tableHeader) {
    display: flex;
    align-items: center;
}

:deep(.status-point) {
    --status-bgcolor: #ffd500;

    &::before {
        content: '';
        display: inline-block;
        width: 8px;
        height: 8px;
        margin-right: 8px;
        background-color: var(--status-bgcolor);
        border-radius: 4px;
    }
}

:deep(.tip-box) {
    margin-left: 4px;
}

:deep(.box-item) {
    white-space: pre-line;
}
</style>
